<script setup lang="ts">
import { ref, onMounted, computed } from 'vue'
import { useRouter } from 'vue-router'
import { useTransactionStore } from '@/stores/transaction'
import { useCategoryStore } from '@/stores/category'
import type { Transaction } from '@/types'
import { ACCOUNT_TYPES, CATEGORY_ICONS } from '@/types'
import { showToast } from 'vant'
import dayjs from 'dayjs'

const router = useRouter()
const transactionStore = useTransactionStore()
const categoryStore = useCategoryStore()

// 表单数据
const form = ref({
  type: 'expense' as 'income' | 'expense',
  amount: '',
  categoryId: 0,
  description: '',
  date: dayjs().format('YYYY-MM-DD'),
  time: dayjs().format('HH:mm'),
  account: 'cash' as keyof typeof ACCOUNT_TYPES
})

// 显示控制
const showCategoryPicker = ref(false)
const showDatePicker = ref(false)
const showTimePicker = ref(false)
const showAccountPicker = ref(false)

// 计算属性
const availableCategories = computed(() => {
  return form.value.type === 'income' 
    ? categoryStore.incomeCategories 
    : categoryStore.expenseCategories
})

const selectedCategory = computed(() => {
  return categoryStore.getCategoryById(form.value.categoryId)
})

const accountOptions = computed(() => {
  return [Object.entries(ACCOUNT_TYPES).map(([key, value]) => ({
    text: value,
    value: key
  }))]
})

onMounted(async () => {
  await categoryStore.fetchCategories()
  if (categoryStore.categories.length === 0) {
    await categoryStore.initializeCategories()
  }
})

const onTypeChange = () => {
  form.value.categoryId = 0 // 重置分类选择
}

const onCategoryConfirm = (options: any) => {
  const selectedOption = options.selectedOptions[0]
  if (selectedOption) {
    form.value.categoryId = selectedOption.value
  }
  showCategoryPicker.value = false
}

const onDateConfirm = ({ selectedValues }: any) => {
  form.value.date = selectedValues.join('-')
  showDatePicker.value = false
}

const onTimeConfirm = (time: string) => {
  form.value.time = time
  showTimePicker.value = false
}

const onAccountConfirm = (options: any) => {
  const selectedOption = options.selectedOptions[0]
  if (selectedOption) {
    form.value.account = selectedOption.value
  }
  showAccountPicker.value = false
}

const onSubmit = async () => {
  if (!form.value.amount || parseFloat(form.value.amount) <= 0) {
    showToast('请输入有效金额')
    return
  }

  if (!form.value.categoryId) {
    showToast('请选择分类')
    return
  }

  try {
    const datetime = dayjs(`${form.value.date} ${form.value.time}`).toDate()
    
    const transactionData: Omit<Transaction, 'id'> = {
      type: form.value.type,
      amount: parseFloat(form.value.amount),
      categoryId: form.value.categoryId,
      description: form.value.description,
      date: datetime,
      account: form.value.account
    }

    await transactionStore.createTransaction(transactionData)
    router.back()
  } catch (error) {
    console.error('添加失败:', error)
  }
}

const categoryPickerOptions = computed(() => {
  return [availableCategories.value.map(category => ({
    text: category.name,
    value: category.id
  }))]
})
</script>

<template>
  <div class="add-transaction-view">
    <van-nav-bar 
      title="记一笔" 
      left-text="取消" 
      right-text="保存"
      @click-left="router.back()"
      @click-right="onSubmit"
    />

    <div class="form-container">
      <!-- 收支类型切换 -->
      <van-cell-group>
        <van-cell title="类型">
          <template #value>
            <van-radio-group v-model="form.type" direction="horizontal" @change="onTypeChange">
              <van-radio name="expense" checked-color="#FF5722">支出</van-radio>
              <van-radio name="income" checked-color="#4CAF50">收入</van-radio>
            </van-radio-group>
          </template>
        </van-cell>
      </van-cell-group>

      <!-- 金额输入 -->
      <van-cell-group>
        <van-field
          v-model="form.amount"
          type="number"
          label="金额"
          placeholder="0.00"
          :border="false"
          class="amount-field"
        >
          <template #left-icon>
            <span class="currency-symbol">¥</span>
          </template>
        </van-field>
      </van-cell-group>

      <!-- 分类选择 -->
      <van-cell-group>
        <van-cell 
          title="分类" 
          :value="selectedCategory?.name || '请选择分类'"
          is-link
          @click="showCategoryPicker = true"
        >
          <template #icon v-if="selectedCategory">
            <span class="category-icon">
              {{ CATEGORY_ICONS[selectedCategory.icon as keyof typeof CATEGORY_ICONS] || CATEGORY_ICONS.default }}
            </span>
          </template>
        </van-cell>
      </van-cell-group>

      <!-- 备注 -->
      <van-cell-group>
        <van-field
          v-model="form.description"
          type="textarea"
          label="备注"
          placeholder="添加备注（可选）"
          rows="2"
          maxlength="200"
          show-word-limit
        />
      </van-cell-group>

      <!-- 日期时间 -->
      <van-cell-group>
        <van-cell 
          title="日期" 
          :value="form.date"
          is-link
          @click="showDatePicker = true"
        />
        <van-cell 
          title="时间" 
          :value="form.time"
          is-link
          @click="showTimePicker = true"
        />
      </van-cell-group>

      <!-- 账户 -->
      <van-cell-group>
        <van-cell 
          title="账户" 
          :value="ACCOUNT_TYPES[form.account]"
          is-link
          @click="showAccountPicker = true"
        />
      </van-cell-group>

      <!-- 提交按钮 -->
      <div class="submit-button">
        <van-button 
          type="primary" 
          size="large" 
          block 
          :loading="transactionStore.loading"
          @click="onSubmit"
        >
          保存
        </van-button>
      </div>
    </div>

    <!-- 分类选择器 -->
    <van-popup v-model:show="showCategoryPicker" position="bottom">
      <van-picker
        :columns="categoryPickerOptions"
        @confirm="onCategoryConfirm"
        @cancel="showCategoryPicker = false"
      />
    </van-popup>

    <!-- 日期选择器 -->
    <van-popup v-model:show="showDatePicker" position="bottom">
      <van-date-picker
        v-model="form.date"
        title="选择日期"
        :min-date="new Date(2020, 0, 1)"
        :max-date="new Date()"
        @confirm="onDateConfirm"
        @cancel="showDatePicker = false"
      />
    </van-popup>

    <!-- 时间选择器 -->
    <van-popup v-model:show="showTimePicker" position="bottom">
      <van-time-picker
        :model-value="form.time"
        @confirm="onTimeConfirm"
        @cancel="showTimePicker = false"
      />
    </van-popup>

    <!-- 账户选择器 -->
    <van-popup v-model:show="showAccountPicker" position="bottom">
      <van-picker
        :columns="accountOptions"
        @confirm="onAccountConfirm"
        @cancel="showAccountPicker = false"
      />
    </van-popup>
  </div>
</template>

<style scoped>
.add-transaction-view {
  background-color: #f5f5f5;
  min-height: 100vh;
}

.form-container {
  padding: 16px;
}

.amount-field {
  font-size: 24px;
  font-weight: bold;
}

.currency-symbol {
  font-size: 24px;
  font-weight: bold;
  color: #333;
  margin-right: 8px;
}

.category-icon {
  font-size: 20px;
  margin-right: 8px;
}

.submit-button {
  margin-top: 32px;
}

.van-cell-group {
  margin-bottom: 16px;
}
</style>